package org.e_gold.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.e_gold.dao.UserAccountDAO;
import org.e_gold.model.UserAccount;
import org.e_gold.service.UserAccountService;
import org.e_gold.util.Bet365;
import org.e_gold.util.CalcUtil;
import org.e_gold.util.Constant;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserAccountServiceImpl extends _NavigatorService implements UserAccountService, Constant, Bet365 {

    private static final Logger logger = Logger.getLogger(UserAccountServiceImpl.class);

    @Autowired
    private UserAccountDAO userAccountDAO;

    public boolean isLogined() {

        try {
            Document memberAreaPage = redirectNavigator(DEFAULT_URL);
            Element navMenu = memberAreaPage.select("#NavMenu").get(0);
            for (Element menu : navMenu.select("a")) {
                if (menu.html().equalsIgnoreCase(BALANCE)) {
                    if (!StringUtils.isEmpty(menu.attr("href"))) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
        return false;
    }

    @Override
    public Float getBalance() {

        UserAccount user = getUser();
        if (user != null) {
            return user.getBalance();
        }
        return 0F;
    }

    @Override
    public UserAccount getUser() {

        return userAccountDAO.getCurrentUser();
    }

    @Override
    public Float getRealBalance() {

        Float realBalance = 0f;
        try {
            while (!isLogined()) {
                loginAccount();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Document balancePage = redirectNavigator(BALANCE_URL);
            String balanceStr = balancePage.select(".MidGrey").get(0).select(".spanPadRight strong").text();
            realBalance = CalcUtil.convertBalance(balanceStr);
        } catch (Exception e) {
            logger.error(e);
        }

        return realBalance;
    }

    @Override
    public void loginAccount() {

        try {
            Document loginPage = redirectNavigator(LOGIN_URL);

            Element loginForm = loginPage.getElementById("aspnetForm");
            // prepare login data
            Map<String, String> loginData = prepareLoginData(loginForm);
            postForm(BASE_URL + loginForm.attr("action"), loginData);
        } catch (Exception e) {
            logger.error(e);
        }
    }

    private Map<String, String> prepareLoginData(Element loginForm) {

        Map<String, String> loginData = new HashMap<String, String>();
        loginData.put("txtUsername", "lamhanh86");
        loginData.put("txtPassword", "qwert12345");
        for (Element e : loginForm.select("input[type=hidden]")) {
            loginData.put(e.attr("name"), e.attr("value"));
        }
        headers.put(CONTENT_TYPE, CONTENT_TYPE_DATA);
        headers.put(ORIGIN, "");
        headers.put(COOKIE, cookies.getCookie());
        return loginData;
    }

    @Override
    public void login() {

        while (!isLogined()) {
            loginAccount();
            try {
                Thread.sleep(CalcUtil.randomTime(3, 5) * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
